﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Threading;

/// <summary>
/// Summary description for CountryHelper
/// </summary>
public class CountryHelper
{
    public static List<string> GetCountries()
    {
        List<string> result = new List<string>();

        foreach (KeyValuePair<string, List<string>> item in CountriesDic)
        {
            result.Add(item.Key);
        }
        return result;
    }

    private static Dictionary<string, List<string>> countriesDic;

    public static Dictionary<string, List<string>> CountriesDic
    {
        get
        {
            if (countriesDic == null)
            {
                countriesDic = LoadCountries();
            }
            return countriesDic;
        }
    }

    private static Dictionary<string, List<string>> LoadCountries()
    {
        Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
        XmlDocument countryDoc = new XmlDocument();
        string countryFile = HttpContext.Current.Server.MapPath("CountryList.xml");
        countryDoc.Load(countryFile);
        foreach (XmlNode item in countryDoc.ChildNodes[0].ChildNodes)
        {
            string Country = item.Attributes["CountryName"].InnerText;
            string City = item.Attributes["City"].InnerText;
            City = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(City.ToLower());
            Country = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Country.ToLower());
            List<string> cityList;
            if (result.ContainsKey(Country))
            {
                cityList = result[Country];
                cityList.Add(City);

            }
            else
            {
                cityList = new List<string>();
                cityList.Add(City);
                result.Add(Country, cityList);
            }
        }
        return result;
    }

    public static List<string> GetCitiesByCountry(string countryName, int MaxNumber)
    {
        List<string> result;
        List<string> tempresult;
        tempresult = GetCitiesByCountry(countryName);
        if (tempresult.Count > MaxNumber)
        {
            result = new List<string>();
            Random rand = new Random();
            int randomInt = rand.Next(0, tempresult.Count - 1 - MaxNumber);
            result.AddRange(tempresult.GetRange(randomInt, MaxNumber));
        }
        else
        {
            result = tempresult;
        }

        return result;

    }

    public static List<string> GetCitiesByCountry(string countryName)
    {
        if (CountriesDic.ContainsKey(countryName))
        {
            return CountriesDic[countryName];
        }
        else
        {
            return new List<string>();
        }

    }
}
